package redis

import (
	"app/config"
	"context"
	"fmt"
	"sync"

	"github.com/go-redis/redis/v8"
)

var (
	instances = make(map[string]*redis.Client)
	mu        sync.Mutex
)

func Default() *redis.Client {
	return Get("default")
}

func Get(name string) *redis.Client {
	instance, err := GetInstance(name)
	if err != nil {
		panic(err)
	}
	return instance
}

// GetInstance 获取redis 单例
func GetInstance(name string) (instance *redis.Client, err error) {
	mu.Lock()
	defer mu.Unlock()
	var ok bool
	if instance, ok = instances[name]; ok {
		return instance, nil
	}
	var cfg *config.RedisConfig
	if cfg, ok = config.Config.Redis[name]; !ok {
		return nil, fmt.Errorf("未找到redis配置: %s", name)
	}
	instance = redis.NewClient(&redis.Options{
		Addr:     cfg.Host + ":" + cfg.Port,
		Password: cfg.Password,
		DB:       cfg.Database,
	})
	// 初始化单例对象的状态
	if _, err := instance.Ping(context.TODO()).Result(); err != nil {
		return nil, fmt.Errorf("Redis connection failed: %s", name)
	}
	instances[name] = instance
	return instance, nil
}
